package com.pro01.backend.service;

import com.pro01.backend.mapper.ForumCommentMapper;
import com.pro01.backend.mapper.ForumPostMapper;
import com.pro01.backend.pojo.ForumComment;
import com.pro01.backend.pojo.ForumPost;
import com.pro01.backend.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ForumCommentService {

    @Autowired
    private ForumCommentMapper forumCommentMapper;
    @Autowired
    private NotificationService notificationService;

    @Autowired
    private ForumPostMapper forumPostMapper;

    // 用户发表评论
    public void addComment(ForumComment comment) {
        comment.setStatus("ACTIVE"); // 默认状态
        int result = forumCommentMapper.insertComment(comment);

        // 1. 根据 postId 查询帖子信息
        ForumPost post = forumPostMapper.getPostById(comment.getPostId());
        if (post == null) {
            throw new RuntimeException("帖子不存在");
        }
        Long postOwnerId = post.getUserId();
        String postTitle = post.getTitle();
        Long postId = post.getId();

        // 2. 如果是回复别人的评论，还要查 parentComment
        Long parentCommentOwnerId = null;
        if (comment.getParentCommentId() != null) {
            ForumComment parentComment = forumCommentMapper.getCommentById(comment.getParentCommentId());
            if (parentComment != null) {
                parentCommentOwnerId = parentComment.getUserId();
            }
        }

        // 3. 发通知（评论发完以后）
        if (!comment.getUserId().equals(postOwnerId)) {
            // 评论帖子
            String content = "有人评论了你的帖子：" + postTitle;
            String link = "/posts/" + postId;
            notificationService.sendNotification(postOwnerId, comment.getUserId(), "COMMENT_REPLY", content, link);
        } else if (comment.getParentCommentId() != null && !comment.getUserId().equals(parentCommentOwnerId)) {
            // 回复评论
            String content = "有人回复了你的评论";
            String link = "/posts/" + postId + "#comment-" + comment.getParentCommentId();
            notificationService.sendNotification(parentCommentOwnerId, comment.getUserId(), "COMMENT_REPLY", content, link);
        }

        if (result == 0) {
            throw new RuntimeException("发表评论失败");
        }
    }

    // 用户分页查询评论
    public PageResult<ForumComment> getCommentsByPost(Long postId, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<ForumComment> records = forumCommentMapper.selectCommentsByPost(postId, offset, pageSize);
        int total = forumCommentMapper.countCommentsByPost(postId);
        return new PageResult<>(total, records);
    }

    // 用户删除自己的评论
    public void deleteCommentByUser(Long commentId, Long userId) {
        ForumComment comment = forumCommentMapper.getCommentById(commentId);
        if (comment == null) {
            throw new RuntimeException("评论不存在");
        }
        if (!comment.getUserId().equals(userId)) {
            throw new RuntimeException("无权限删除他人的评论");
        }
        if (!"ACTIVE".equals(comment.getStatus())) {
            throw new RuntimeException("评论已经被删除或隐藏");
        }

        int result = forumCommentMapper.deleteCommentByUser(commentId, userId);
        if (result == 0) {
            throw new RuntimeException("删除评论失败");
        }
    }

    // 用户隐藏自己的评论
    public void hideCommentByUser(Long commentId, Long userId) {
        ForumComment comment = forumCommentMapper.getCommentById(commentId);
        if (comment == null) {
            throw new RuntimeException("评论不存在");
        }
        if (!comment.getUserId().equals(userId)) {
            throw new RuntimeException("无权限隐藏他人的评论");
        }
        if (!"ACTIVE".equals(comment.getStatus())) {
            throw new RuntimeException("只能隐藏处于 ACTIVE 状态的评论");
        }

        int result = forumCommentMapper.hideCommentByUser(commentId, userId);
        if (result == 0) {
            throw new RuntimeException("隐藏评论失败");
        }
    }

    // 用户恢复自己隐藏的评论
    public void restoreCommentByUser(Long commentId, Long userId) {
        ForumComment comment = forumCommentMapper.getCommentById(commentId);
        if (comment == null) {
            throw new RuntimeException("评论不存在");
        }
        if (!comment.getUserId().equals(userId)) {
            throw new RuntimeException("无权限恢复他人的评论");
        }
        if (!"HIDDEN".equals(comment.getStatus())) {
            throw new RuntimeException("只有隐藏状态的评论才能恢复");
        }

        int result = forumCommentMapper.restoreCommentByUser(commentId, userId);
        if (result == 0) {
            throw new RuntimeException("恢复评论失败");
        }
    }

    // 用户查看自己发表的评论
    public PageResult<ForumComment> getMyCommentsByPost(Long postId, Long userId, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<ForumComment> records = forumCommentMapper.selectMyCommentsByPost(postId, userId, offset, pageSize);
        int total = forumCommentMapper.countMyCommentsByPost(postId, userId);
        return new PageResult<>(total, records);
    }

    /**
     * 下面是管理员的接口
     */

    // 删除帖子(仅限管理员)
    public void deleteCommentByAdmin(Long commentId) {
        ForumComment comment = forumCommentMapper.getCommentById(commentId);
        if (comment == null) {
            throw new RuntimeException("评论不存在");
        }
        if ("DELETED".equals(comment.getStatus())) {
            throw new RuntimeException("评论已删除，无需重复删除");
        }

        int result = forumCommentMapper.deleteCommentByAdmin(commentId);
        if (result == 0) {
            throw new RuntimeException("删除评论失败");
        }
    }

    // 隐藏帖子(仅限管理员)
    public void hideCommentByAdmin(Long commentId) {
        ForumComment comment = forumCommentMapper.getCommentById(commentId);
        if (comment == null) {
            throw new RuntimeException("评论不存在");
        }
        if (!"ACTIVE".equals(comment.getStatus())) {
            throw new RuntimeException("只有 ACTIVE 状态的评论才能被隐藏");
        }

        int result = forumCommentMapper.hideCommentByAdmin(commentId);
        if (result == 0) {
            throw new RuntimeException("隐藏评论失败");
        }
    }

    // 恢复帖子(仅限管理员)
    public void restoreCommentByAdmin(Long commentId) {
        ForumComment comment = forumCommentMapper.getCommentById(commentId);
        if (comment == null) {
            throw new RuntimeException("评论不存在");
        }
        if (!"HIDDEN".equals(comment.getStatus()) && !"DELETED".equals(comment.getStatus())) {
            throw new RuntimeException("只有 HIDDEN 或 DELETED 状态的评论才能恢复");
        }

        int result = forumCommentMapper.restoreCommentByAdmin(commentId);
        if (result == 0) {
            throw new RuntimeException("恢复评论失败");
        }
    }


}
